package cn.drh.charging.order.config;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;


/**
 * @ClassName RabbitMQConfiguration
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/6/4 10:39
 * @Version 1.0
 * <p>
 * rabbit-mq 配置类
 * 连接信息 用户名 密码
 * 定义 队列 交换机 并且绑定
 */

@Configuration
public class RabbitMQConfiguration {


    public static final String EXCHANGE_NAME = "charging_order_exchange";

    private static final String QUEUE_NAME = "charging_order_queue";

    public static final String ROUTING_KEY = "charging_order_routing_key";

    private static final String DEAD_LETTER_EXCHANGE_NAME = "charging_dead_letter_order_exchange";

    public static final String DEAD_LETTER_QUEUE_NAME = "charging_dead_order_queue";

    private static final String DEAD_LETTER_ROUTING_KEY = "charging_dead_order_routing_key";

    /**
     * 定义正常订单队列
     *
     * @return Queue
     */
    @Bean
    public Queue orderQueue() {
        HashMap<String, Object> args = new HashMap<>();
        //设置过期时间
        Integer ttl = 2 * 60 * 1000;
        args.put("x-message-ttl", ttl);
        //设置死信队列的交换机名称和RoutingKey,在时间过期后交由死信队列处理
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        //设置是否持久化
        Boolean durable = true;
        //惰性队列，在消息多的时候，将消息存储到磁盘，避免消息积压，缓解内存压力
        args.put("x-queue-mode", "lazy");
        return new Queue(QUEUE_NAME, durable, true, false, args);
    }

    /**
     * 定义正常的交换机
     *
     * @return DirectExchange
     */
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(EXCHANGE_NAME, true, false);
    }

    /**
     * 绑定正常订单队列到正常订单交换机
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(ROUTING_KEY);
    }


    /**
     * 定义死信队列
     *
     * @return Queue
     */
    @Bean
    public Queue orderDeadLetterQueue() {
        return new Queue(DEAD_LETTER_QUEUE_NAME, true, false, false);
    }

    /**
     * 定义死信交换机
     *
     * @return DirectExchange
     */
    @Bean
    public DirectExchange orderDeadLetterExchange() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE_NAME, true, false);
    }

    /**
     * 绑定死信队列到死信交换机
     *
     * @return Binding
     */
    @Bean
    public Binding orderDeadLetterBinding() {
        return BindingBuilder.bind(orderDeadLetterQueue()).to(orderDeadLetterExchange()).with(DEAD_LETTER_ROUTING_KEY);
    }
}
